package com.hzsd.zengbanyi.biaodan_text.Actrivity;

import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hzsd.zengbanyi.biaodan_text.BaseActivity;
import com.hzsd.zengbanyi.biaodan_text.R;
import com.hzsd.zengbanyi.biaodan_text.bean.LabSample;
import com.hzsd.zengbanyi.biaodan_text.bean.LabSpinnerValue;
import com.hzsd.zengbanyi.biaodan_text.bean.ToReceiveSample;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import hzst.android.adapter.CommonAdapter;
import hzst.android.util.JsonDataParser;
import hzst.android.util.NetworkDataUtil;
import hzst.android.view.FooterListView;
import hzst.android.view.FooterListView.OnSlideToBottomListener;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class LabActivity extends BaseActivity implements OnClickListener {
    private RelativeLayout rl_return;
    private Button btn_search;
    private FooterListView listView, listview2;
    private ProgressBar pb_loading;
    private CommonAdapter<LabSample> adapter;
    private CommonAdapter<ToReceiveSample> adapter2;
    private List<LabSample> labSamples;
    private List<ToReceiveSample> toReceiveSamples;
    private List<LabSpinnerValue> labSpinnerValues, toLabSpinnerValues;
    private String urlPath, loginName, name;
    private String searchJson = "";
    private int curPage = 1;
    private int curPage2 = 1;
    private int pageSize = 10;
    private String[] spData, spData2;
    private ArrayAdapter<String> spAdapte = null, spAdapte2 = null;
    private String monitor_unit_name, element_name, entity_name;
    private int spPosion, spPosion2;
    private TextView tv_isReceive;
    private boolean isReceive = false;//是否接受；默认：待接收（false）

    private final int MSG_LIST = 0;
    private final int MSG_SP_DATA = 1;
    private final int MSG_TO_LIST = 2;
    private final int MSG_TO_SP_DATA = 3;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LIST:
                    pb_loading.setVisibility(View.GONE);
                    if (adapter == null) {
                        adapter = new CommonAdapter<LabSample>(LabActivity.this, labSamples, R.layout.item_lab) {
                            public void convert(ViewHolder helper, LabSample item, int position) {
                                helper.setText(R.id.tv_monitor_unit_name, item.getMonitor_unit_name());
                                helper.setText(R.id.tv_scene_start_time, item.getScene_start_time());
                                helper.setText(R.id.tv_sample_code, item.getSample_code());
                                helper.setText(R.id.tv_element_name, item.getElement_name());
                                if (position % 2 != 0) {
                                    helper.setBackground(R.id.ll_list_title, R.color.blue_shallow_1);
                                } else {
                                    helper.setBackground(R.id.ll_list_title, R.color.blue_shallow_2);
                                }
                            }

                            ;
                        };
                        listView.setAdapter(adapter);
                    } else {
                        adapter.notifyDataSetChanged();
                    }
                    listView.loadFooterView();
                    break;
                case MSG_SP_DATA:
                    int size = labSpinnerValues.size();
                    spData = new String[size + 1];
                    spData[0] = "";
                    for (int i = 0; i < size; i++) {
                        spData[i + 1] = labSpinnerValues.get(i).getElement_name();
                    }
                    spAdapte = new ArrayAdapter<String>(LabActivity.this, android.R.layout.simple_spinner_item, spData);
                    spAdapte.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    break;
                case MSG_TO_SP_DATA:
                    int size2 = toLabSpinnerValues.size();
                    spData2 = new String[size2 + 1];
                    spData2[0] = "";
                    for (int i = 0; i < size2; i++) {
                        spData2[i + 1] = toLabSpinnerValues.get(i).getElement_name();
                    }
                    spAdapte2 = new ArrayAdapter<String>(LabActivity.this, android.R.layout.simple_spinner_item, spData2);
                    spAdapte2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    break;

                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lab);
        initBaseData();
        initView();
        initEvents();
        getSpData();
        getToSpData();
        getData();
        getToReceive();
    }

    private void initBaseData() {
        SharedPreferences sp = getSharedPreferences("user", MODE_PRIVATE);
        urlPath = sp.getString("urlPath", "");
        loginName = sp.getString("loginName", "");
        name = sp.getString("name", "");

    }

    private void initView() {
        rl_return = (RelativeLayout) findViewById(R.id.rl_return);
        btn_search = (Button) findViewById(R.id.btn_search);
        pb_loading = (ProgressBar) findViewById(R.id.pb_loading);
        listView = (FooterListView) findViewById(R.id.listview);
        listview2 = (FooterListView) findViewById(R.id.listview2);
        tv_isReceive = (TextView) findViewById(R.id.tv_isReceive);
        listView.setPageSize(pageSize);
        listview2.setPageSize(pageSize);
    }

    private void initEvents() {
        rl_return.setOnClickListener(this);
        btn_search.setOnClickListener(this);
        tv_isReceive.setOnClickListener(this);

        listView.setOnSlideToBottomListener(new OnSlideToBottomListener() {

            @Override
            public void arriveBottom() {
                curPage++;
                getData();

            }
        });
        listview2.setOnSlideToBottomListener(new OnSlideToBottomListener() {

            @Override
            public void arriveBottom() {
                curPage2++;
                getToReceive();

            }
        });

        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Intent intent = new Intent(LabActivity.this, AnalysisActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("task_id", labSamples.get(position).getTask_id());
                bundle.putString("task_scene_id", labSamples.get(position).getTask_scene_id());
                bundle.putString("item_id", labSamples.get(position).getItem_id());
                bundle.putString("sample_code_btn", labSamples.get(position).getSample_code_btn());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        listview2.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Intent intent = new Intent(LabActivity.this, AnalysisActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("task_id", labSamples.get(position).getTask_id());
                bundle.putString("task_scene_id", labSamples.get(position).getTask_scene_id());
                bundle.putString("item_id", labSamples.get(position).getItem_id());
                bundle.putString("sample_code_btn", labSamples.get(position).getSample_code_btn());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

    }

    /**
     * 获取 理化室--样品分析列表 数据
     */
    private void getData() {
        pb_loading.setVisibility(View.VISIBLE);
        new Thread() {
            public void run() {
                if (labSamples == null) {
                    labSamples = new ArrayList<LabSample>();
                }
                String url = "http://" + urlPath + "/ServiceInterface/OriginalRecord/RecordList.ashx?curPage=" + curPage + "&pageSize=" + pageSize + "&orderBy=task_code&orderByRole=desc&searchFilter=" + URLEncoder.encode(searchJson) + "&u_code=" + loginName;
                System.out.println("理化室--样品分析列表：" + url);
                String json = NetworkDataUtil.getJsonData(url);
                JsonDataParser.getBeanList(json, LabSample[].class, labSamples);
                Message msg = Message.obtain();
                msg.what = MSG_LIST;
                handler.sendMessage(msg);
            }

            ;
        }.start();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_return:
                finish();
                break;
            case R.id.btn_search:
                searchDialog();
                break;
            case R.id.tv_isReceive:
                if (isReceive) {
                    tv_isReceive.setText("待接收样品");
                    listView.setVisibility(View.VISIBLE);
                    listview2.setVisibility(View.GONE);
                    isReceive = false;
                } else {
                    tv_isReceive.setText("已接收样品");
                    listView.setVisibility(View.GONE);
                    listview2.setVisibility(View.VISIBLE);
                    isReceive = true;
                }
                break;

            default:
                break;
        }

    }

    public void searchDialog() {
        View view = LayoutInflater.from(LabActivity.this).inflate(R.layout.lab_search, null, false);
        final EditText et_monitor_unit_name = (EditText) view.findViewById(R.id.et_monitor_unit_name);
        final Spinner sp_element_name = (Spinner) view.findViewById(R.id.sp_element_name);
        final Spinner sp_element_name2 = (Spinner) view.findViewById(R.id.sp_element_name2);
        final EditText et_entity_name = (EditText) view.findViewById(R.id.et_entity_name);

        et_monitor_unit_name.setText(monitor_unit_name);
        et_entity_name.setText(entity_name);
        if (isReceive) {
            sp_element_name.setAdapter(spAdapte);
            sp_element_name.setVisibility(View.VISIBLE);
            sp_element_name2.setVisibility(View.GONE);
        } else {
            sp_element_name2.setAdapter(spAdapte2);
            sp_element_name.setVisibility(View.GONE);
            sp_element_name2.setVisibility(View.VISIBLE);
        }

        sp_element_name.setSelection(spPosion);
        sp_element_name2.setSelection(spPosion2);

        Builder builder = new Builder(LabActivity.this);
        builder.setTitle("搜索");
        builder.setView(view);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setPositiveButton("查询", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                monitor_unit_name = et_monitor_unit_name.getText().toString().trim();
                if (isReceive) {
                    element_name = sp_element_name.getSelectedItem().toString().trim();
                } else {
                    element_name = sp_element_name2.getSelectedItem().toString().trim();
                }

                entity_name = et_entity_name.getText().toString().trim();
                spPosion = sp_element_name.getSelectedItemPosition();
                spPosion2 = sp_element_name2.getSelectedItemPosition();

                Map<String, String> map = new HashMap<String, String>();
                map.put("monitor_unit_name", monitor_unit_name);
                map.put("element_name", element_name);
                map.put("entity_name", entity_name);
                Gson gson = new Gson();
                searchJson = gson.toJson(map);
                if (isReceive) {
//					refresh();
                    refresh2();
                } else {
//					refresh2();
                    refresh();
                }

            }
        });
        builder.create().show();
    }

    /**
     * 刷新
     */
    public void refresh() {
        curPage = 1;
        labSamples.clear();
        adapter.notifyDataSetChanged();
        listView.loadFooterView();
        getData();
    }

    public void refresh2() {
        curPage2 = 1;
        toReceiveSamples.clear();
        adapter2.notifyDataSetChanged();
        listview2.loadFooterView();
        getToReceive();
    }

    /**
     * 获取Spinner的下拉数据--已接收样品
     */
    public void getSpData() {
        new Thread() {
            public void run() {
                if (labSpinnerValues == null) {
                    labSpinnerValues = new ArrayList<LabSpinnerValue>();
                }
                String url = "http://" + urlPath + "/ServiceInterface/OriginalRecord/GetItem.ashx?method=Received&usercode=" + loginName;
                System.out.println("已接收--监测项目：" + url);
                JsonDataParser.getBeanList(NetworkDataUtil.getJsonData(url), LabSpinnerValue[].class, labSpinnerValues);
                Message msg = Message.obtain();
                msg.what = MSG_SP_DATA;
                handler.sendMessage(msg);
            }

            ;
        }.start();
    }

    /**
     * 获取Spinner的下拉数据--待接收样品
     */
    public void getToSpData() {
        new Thread() {
            public void run() {
                if (toLabSpinnerValues == null) {
                    toLabSpinnerValues = new ArrayList<LabSpinnerValue>();
                }
                String url = "http://" + urlPath + "/ServiceInterface/OriginalRecord/GetItem.ashx?method=ToReceive&usercode=" + loginName;
                System.out.println("待接收--监测项目：" + url);
                JsonDataParser.getBeanList(NetworkDataUtil.getJsonData(url), LabSpinnerValue[].class, toLabSpinnerValues);
                Message msg = Message.obtain();
                msg.what = MSG_TO_SP_DATA;
                handler.sendMessage(msg);
            }

            ;
        }.start();
    }

    /**
     * 待接收样品--数据集合获取
     */
    public void getToReceive() {
        if (toReceiveSamples == null) {
            toReceiveSamples = new ArrayList<ToReceiveSample>();
        }
        String url = "http://" + urlPath + "/ServiceInterface/OriginalRecord/ToReceiveSample.ashx?" + "curPage=" + curPage2 + "&pageSize=" + pageSize + "&searchFilter=" + URLEncoder.encode(searchJson) + "&u_name=" + URLEncoder.encode(name);
        Observable.just(url)
                .map(new Func1<String, String>() {

                    @Override
                    public String call(String url) {
                        System.out.println("待接收样品：" + url);
                        JsonDataParser.getBeanList(NetworkDataUtil.getJsonData(url), ToReceiveSample[].class, toReceiveSamples);
                        return null;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {

                    @Override
                    public void call(String arg0) {
                        initToReceiveAdapter();

                    }
                });
    }

    public void initToReceiveAdapter() {
        if (adapter2 == null) {
            adapter2 = new CommonAdapter<ToReceiveSample>(LabActivity.this, toReceiveSamples, R.layout.item_lab) {
                @Override
                public void convert(
                        ViewHolder helper,
                        ToReceiveSample item, int position) {
                    helper.setText(R.id.tv_monitor_unit_name, item.getMonitor_unit_name());
                    helper.setText(R.id.tv_scene_start_time, item.getScene_start_time());
                    helper.setText(R.id.tv_sample_code, item.getSample_code_list());
                    helper.setText(R.id.tv_element_name, item.getElement_name());
                    if (position % 2 != 0) {
                        helper.setBackground(R.id.ll_list_title, R.color.blue_shallow_1);
                    } else {
                        helper.setBackground(R.id.ll_list_title, R.color.blue_shallow_2);
                    }
                }
            };
            listview2.setAdapter(adapter2);
        } else {
            adapter2.notifyDataSetChanged();
        }
        listview2.loadFooterView();
    }
}
